package com.qingzhu.service.impl;

import com.qingzhu.dao.*;
import com.qingzhu.dao.impl.*;
import com.qingzhu.pojo.*;
import com.qingzhu.pojovo.OrderVo;
import com.qingzhu.service.AddressService;
import com.qingzhu.service.OrderService;
import com.qingzhu.service.ShopOptionService;
import com.qingzhu.util.CreateCustomPage;

import java.util.*;

public class OrderServiceImpl implements OrderService {
    OrderDao orderDao = new OrderDaoImpl();
    OrderItemDao orderItemDao = new OrderItemDaoImpl();
    ReceivingAddressDao receivingAddressDao = new ReceivingAddressDaoImpl();
    UserDao userDao = new UserDaoImpl();
    AddressService addressService = new AddressServiceImpl();
    ShopOptionService shopOptionService = new ShopOptionServiceImpl();
    GoodsDao goodsDao = new GoodsDaoImpl();

    @Override
    public OrderVo createOrder(ShopCart shopCart, String id) {
        // 查询到用户的收货地址
        ReceivingAddress receivingAddress = receivingAddressDao.findById(Integer.parseInt(id));
        // 查找完整的地址
        Address defaultAddress = addressService.findDefaultAddress(receivingAddress.getRegionUrl());
        receivingAddress.setRegion(defaultAddress);
        // 查找用户信息
        User user = userDao.findById(receivingAddress.getUserId());
        // 生成订单
        Order orderEntity = createOrderEntity(shopCart, receivingAddress, user);
        int insterOrderResult = orderDao.insterOrder(orderEntity);
        // 处理购物车并生成订单商品信息
        OrderVo orderVo = createCart(shopCart, orderEntity);
        int orderItemResult = 0;
        List<OrderItem> orderItems = orderVo.getOrderItems();
        for (int i=0; i<orderItems.size(); i++) {
            int oiResult = orderItemDao.insterOrderItem(orderItems.get(i));
            if (oiResult > 0) {
                orderItemResult ++;
            }
        }
        // 如果订单和订单商品列表都生成成功表示订单创建成功
        if (insterOrderResult >0 && orderItemResult>0) {
            orderVo.setResult(1);
        }else {
            orderVo.setResult(0);
        }
        orderVo.setOrder(orderEntity);
        return orderVo;
    }

    @Override
    public CustomPage<OrderVo> findOrderAll(String status, int userId, int pageNum, int pageSize) {
        List<Order> orders = null;
        // 如果status标记为-1则查询已经被删除的订单记录,否则查找正常记录
        if (status.equals("-1")) {
            orders = orderDao.findDelOrderAll(userId);
        }else {
            orders = orderDao.findOrderAll(status,userId);
        }
        List<OrderVo> orderVoList = new ArrayList<>();
        // 查询订单关联的商品信息
        if (orders != null) {
            orders.forEach(order -> {
                // 封装订单
                OrderVo orderVo = new OrderVo();
                orderVo.setOrder(order);
                // 封装商品列表
                List<OrderItem> orderItems = orderItemDao.findOrderItemByOrderId(order.getOrderId());
                orderVo.setOrderItems(orderItems);
                // 添加到订单列表
                orderVoList.add(orderVo);
            });
        }
        /* 自定义逻辑分页 */
        CustomPage<OrderVo> page = new CreateCustomPage<OrderVo>().createPage(orderVoList, pageNum, pageSize);
        return page;
    }

    @Override
    public CustomPage<OrderVo> searckOrder(String selectType, String searchInput, int userId, int pageNum, int pageSize) {
        List<OrderVo> orderVoList = new ArrayList<>();
        if (selectType.equals("1")){
            // 根据订单号搜索
            OrderVo orderVo = new OrderVo();
            Order order = orderDao.findOrderById(searchInput,userId);
            orderVo.setOrder(order);
            if (order != null) {
                // 封装商品列表
                List<OrderItem> orderItems = orderItemDao.findOrderItemByOrderId(order.getOrderId());
                orderVo.setOrderItems(orderItems);
                orderVoList.add(orderVo);
            }
        }else {
            // 储存订单的id(这里使用HashSet对id进行去重)
            Set<Integer> orderIds = new HashSet<>();
            // 根据关键字先到商品的标题查找
            List<OrderItem> orderItems = orderItemDao.findOrderItemByKey(searchInput);
            if (orderItems.size() > 0) {
                orderItems.forEach(orderItem -> {
                    // 把订单的id取出
                    orderIds.add(orderItem.getOrderId());
                });
                // 根据订单id把所有的订单查询出来
                orderIds.forEach(orderId -> {
                    OrderVo orderVo = new OrderVo();
                    Order order = orderDao.findOrderById(String.valueOf(orderId),userId);
                    // 因为查询到的订单id可能包含被删除的或者其他用户的订单，所以要忽略这些订单
                    if (order != null) {
                        orderVo.setOrder(order);
                        List<OrderItem> orderItemList = orderItemDao.findOrderItemByOrderId(order.getOrderId());
                        orderVo.setOrderItems(orderItemList);
                        orderVoList.add(orderVo);
                    }
                });
            }
        }
        /* 自定义逻辑分页 */
        CustomPage<OrderVo> page = new CreateCustomPage<OrderVo>().createPage(orderVoList, pageNum, pageSize);
        return page;
    }

    @Override
    public int deleteOrderById(int orderId) {
        return orderDao.deleteOrderById(orderId);
    }

    @Override
    public int recoveryOrderById(int orderId) {
        return orderDao.recoveryOrderById(orderId);
    }


    // 生成订单实体
    private Order createOrderEntity (ShopCart shopCart, ReceivingAddress receivingAddress,User user) {
        Order order = new Order();
        // 实付金额
        order.setPayment(shopCart.getSunShopPrice());
        // 设置付款状态(1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭,7、待评价)
        order.setStatus("1");
        // 获取当前的日期
        Calendar calendar = Calendar.getInstance();
        order.setCreateTime(calendar.getTime());
        order.setUpdateTime(calendar.getTime());
        order.setUserId(receivingAddress.getUserId());
        order.setBuyerNick(user.getNickName());
        order.setBuyerRate("否");
        // 拼接用户的收货地址
        String rap = receivingAddress.getRegion().getProvinces().getProvince();
        String rac = receivingAddress.getRegion().getCities().getCity();
        String raa = receivingAddress.getRegion().getAreas().getArea();
        String dra = receivingAddress.getDetailedAddress();
        String ra = rap+" "+rac+" "+raa+" "+dra;
        order.setReceiverAreaName(ra);
        order.setReceiverMobile(receivingAddress.getPhone());
        order.setReceiver(receivingAddress.getConsignee());
        // 发票类型(1普通发票，2电子发票，3增值税发票)
        order.setInvoiceType("1");
        return order;
    }
    // 将生成订单的商品从购物车中移除并生成订单商品列表
    private OrderVo createCart(ShopCart shopCart, Order order){
        OrderVo orderVo = new OrderVo();
        List<OrderItem> orderItems = new ArrayList<>();
        List<Integer> itemIds = new LinkedList<>();
        shopCart.getShopOptions().forEach(shopOption -> shopOption.getItems().forEach(itemOption -> {
            if (itemOption.getIsChecked()) {
                OrderItem orderItem = createOrderItem(order, itemOption);
                orderItems.add(orderItem);
                itemIds.add(itemOption.getItem().getId());
            }
        }));
        // 移除被选中的购物车
        shopCart = shopOptionService.removeShopSption(shopCart,itemIds);
        orderVo.setOrderItems(orderItems);
        if (shopCart.getShopOptions().size()>0) {
            orderVo.setShopCart(shopCart);
        }else {
            orderVo.setShopCart(null);
        }
        return orderVo;
    }
    // 生成订单商品表
    private OrderItem createOrderItem(Order order, ItemOption itemOption){
        OrderItem orderItem = new OrderItem();
        orderItem.setItemId(itemOption.getItem().getId());
        orderItem.setOrderId(order.getOrderId());
        Goods goods = goodsDao.findGoodsById(itemOption.getItem().getGoodsId(),true);
        orderItem.setTitle(goods.getTitle());
        orderItem.setPrice(itemOption.getItem().getPrice());
        orderItem.setNum(itemOption.getShopNum());
        orderItem.setTotalFee(itemOption.getItem().getPrice()*itemOption.getShopNum());
        orderItem.setPicPath(itemOption.getItem().getImage());
        return orderItem;
    }
}
